package 笔试题;

import java.util.Arrays;

class Nm {

    // 第一题是一个方法，入参int i，i是小于20的一个数，返回值为String，方法描述，求n!，比如输入5，输出是120。
    public static String run(int n){
        // 求n!
        // 5 * 4 * 3 * 2 * 1 = ?
        int i = 2;

        long answer = 1L;

        while (i <= n){
            answer *= i;
            i++;
        }

        return "" + answer;
    }

    public static String run2(int n){
        // 求n!
        // 5 * 4 * 3 * 2 * 1 = ?
        int i = 2;

//        long answer = 1L;
        String answer = "1";

        while (i <= n){
//            answer *= i;
            answer = compute(answer,i);
            i++;
        }

        return "" + answer;
    }

    public static String compute(String answer,int i){
        // 按位相乘 超出进一
        // answer = 12;i = 2
        char[] chars = answer.toCharArray();
        int pre = 0;
        int num = 0;

        StringBuilder stringBuilder = new StringBuilder();


        int j = chars.length - 1;
        while (j >= 0 || pre != 0){
            char b = ' ';
            if (j>=0){
                b = chars[j];
            }
            num = ((j>=0)?((chars[j] - 48) * i):0) + pre;
            pre = 0;
            if (num > 10){
                pre = num/10;
                num = num%10;
            }
            j--;
            stringBuilder.append(num);
        }

        System.out.println(stringBuilder.reverse());
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        int num = 20;
        String answer = run(num);
        System.out.println("run(" + num + ") = " + answer);
//        System.out.println("run2(" + num + ") = " + "121645100408832000");
//        System.out.println(answer.equals("121645100408832000"));
        //2432902008176640000

//        System.out.println("compute(\"6402373705728000\",19) = " + compute("6402373705728000", 19));
//        System.out.println("compute(\"6402373705728000\",19) = 121645100408832000");
        // todo 目前只能计算20位以内的
    }
}
